#include "labellistmodel.h"

#include "vertexitem.h"

LabelListModel::LabelListModel(QObject *parent)
    : QAbstractListModel(parent)
{

}

int LabelListModel::rowCount(const QModelIndex &parent) const
{
    //父项
    if (parent.isValid())
        return 0;
    return myItems.size();
}

//根据role返回对应的data
QVariant LabelListModel::data(const QModelIndex &index, int role) const
{
    //index的结构？
    if (!index.isValid() || index.row() >= myItems.size())
        return QVariant();
    //data是一个结构体
    const SceneItemData &data = myItems.at(index.row());
    if (role == Qt::DisplayRole) {
        return data.text;
    } else if (role == Qt::CheckStateRole) {
        return data.visible ? Qt::Checked : Qt::Unchecked;
    }
    return QVariant();
}

bool LabelListModel::setData(const QModelIndex &index, const QVariant &value, int role)
{
    if (!index.isValid() || index.row() >= myItems.size())
        return false;

    SceneItemData &data = myItems[index.row()];
    if (role == Qt::CheckStateRole) {
        bool vis = (value.toInt() == Qt::Checked);
        data.visible = vis;
        if(data.item)
        {
            data.item->setVisible(vis);
            for (VertexItem* item: data.item->vertexes())
            {
                item->setVisible(vis);
            }
        }

        emit dataChanged(index, index, {role});
        return true;
    } else if (role == Qt::EditRole) {
        data.text = value.toString();
        if(data.item)
            data.item->setText(data.text);
        emit dataChanged(index, index, {role});
        return true;
    }
    return false;
}

Qt::ItemFlags LabelListModel::flags(const QModelIndex &index) const
{
    if (!index.isValid())
        return Qt::NoItemFlags;
    return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable | Qt::ItemIsUserCheckable;
}

void LabelListModel::addItem(PolygonItem *item, const QString &text)
{
    //顶层插入
    beginInsertRows(QModelIndex(), myItems.size(), myItems.size());
    SceneItemData data;
    data.item = item;
    data.text = text;
    data.visible = item->isVisible();
    myItems.append(data);
    endInsertRows();

    if (myLabelModel)
        myLabelModel->tryAddName(item->text());

}

void LabelListModel::removeItem(PolygonItem *item)
{
    int idx = indexOf(item);
    if(idx >= 0) {
        beginRemoveRows(QModelIndex(), idx, idx);
        myItems.removeAt(idx);
        endRemoveRows();
    }
    if (myLabelModel)
        myLabelModel->tryRemoveName(item->text());

}



int LabelListModel::indexOf(PolygonItem *item) const
{
    for (int i = 0; i < myItems.size(); i++) {
        if (myItems[i].item == item)
            return i;
    }
    return -1;
}

void LabelListModel::setLabelNameList(LabelNameListModel *labelModel)
{
    myLabelModel = labelModel;
}

void LabelListModel::clear() {
    beginResetModel();
    if(!myItems.isEmpty())
    {
       myItems.clear();
    }

    endResetModel();
}
